package com.fishingwithme.infrastructure;

import com.fishingwithme.infrastructure.utils.JwtUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import com.fishingwithme.infrastructure.dtos.DTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fishingwithme.infrastructure.utils.ObjectMapperFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WeChatLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private ObjectMapperFactory objectMapperFactory;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        FwmUserDetails userDetails = (FwmUserDetails) authentication.getDetails();
        String jwt = jwtUtils.generateJwtToken(userDetails);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        List<String> roles = userDetails.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();

       
        ObjectMapper mapper = objectMapperFactory.getInstance();
 
        Map<String,Object> userInfo = new HashMap<>();

        userInfo.put("nickname", userDetails.getNickname());
        userInfo.put("id", userDetails.getUserId()+"");
        userInfo.put("username", userDetails.getUsername());
        userInfo.put("avatarUrl", userDetails.getAvatarUrl());
        userInfo.put("roles",  roles);
        userInfo.put("token", jwt);

         DTO<Map<String,Object>> dto = DTO.success(userInfo);
                 mapper.writeValue(response.getWriter(), dto);

    }
}